<template>
  <a-layout id="layout-container">
    <a-layout-sider v-model:collapsed="collapsed" :trigger="null" collapsible>
      <div class="logo">过往</div>
      <a-timeline class="history">
        <a-timeline-item :key="item.id" v-for="item in historyData">
          <a href="#" v-on:click="search(item)">{{ item.msg }}</a>
        </a-timeline-item>
      </a-timeline>
    </a-layout-sider>
    <a-layout>
      <a-layout-header style="background: #fff; padding: 0">
        <menu-unfold-outlined
          v-if="collapsed"
          class="trigger"
          @click="() => (collapsed = !collapsed)"
        />
        <menu-fold-outlined v-else class="trigger" @click="() => (collapsed = !collapsed)" />
        <span class="currentUser">当前用户：{{ formData.userId }}</span>
      </a-layout-header>
      <a-layout-content
        id="content-container"
        :style="{
          fontSize: '25px',
          margin: '10px 10px',
          padding: '10px',
          background: '#fff',
          minHeight: '400px',
        }"
      >
        <div id="chat-msgs-container">
          <div class="self-msg-container">
            <p v-if="myMsg" class="self-msg">{{ myMsg }}</p>
          </div>
          <div id="ai-msg-container" class="ai-msg-container">
            <div v-html="responseData" class="ai-msg"></div>
          </div>
        </div>
      </a-layout-content>
      <a-layout-footer
        id="footer-container"
        :style="{ height: '200px', margin: '10px 10px', padding: '10px', background: '#fff' }"
      >
        <a-form
          :model="formData"
          name="basic"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
        >
          <a-form-item style="position: relative" id="message-input-container" name="message">
            <a-textarea allowClear style="height: 100%" v-model:value="formData.msg" />
            <a-button
              style="
                height: 50px;
                width: 100px;
                font-size: 20px;
                border-radius: 20px;
                position: fixed;
                right: 28px;
                bottom: 30px;
                z-index: 999;
              "
              type="primary"
              html-type="submit"
              >提交</a-button
            >
          </a-form-item>
        </a-form>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
const collapsed = ref(false)
import { onMounted, ref, reactive } from 'vue'
import request from '@/utils/request'
import { ai } from '@/api/sse.js'
import { getAllData } from '@/api/history.js'
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons-vue'

const historyData = ref([])
// 当页面加载完成时立即自动执行的函数
onMounted(async () => {
  const res = await request.get('user/check-login')
  console.log(res.loginId)
  formData.userId = res.loginId
  initSSE(res.loginId)
  historyData.value = await getAllData()
})
const myMsg = ref('')
const formData = reactive({
  userId: 'admin',
  msg: '你是谁？',
})

const responseData = ref('')

const search = async (item) => {
  myMsg.value = item.msg
  responseData.value = item.answer
  console.log(responseData.value)
}

const onFinish = async () => {
  myMsg.value = formData.msg
  responseData.value = ''
  const res = await ai(formData)
  console.log(res)
}
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}

const initSSE = (userId) => {
  let source = null
  if (window.EventSource) {
    // 建立连接
    source = new EventSource('http://127.0.0.1:8080/sse/connect?userId=' + userId)
    source.addEventListener(
      'open',
      function (e) {
        console.log(e, '建立连接...')
      },
      false,
    )
    source.addEventListener('add', function (e) {
      responseData.value += e.data
      var dom = document.getElementById('ai-msg-container')
      dom.scrollTop = dom.scrollHeight
      console.log(e.data)
    })

    source.addEventListener('finish', function (e) {
      console.log(e, 'finish事件...')
    })
    source.addEventListener('error', function (e) {
      console.log('error事件...')
      console.log('e.readyState: ' + source.readyState)
      if (e.readyState === EventSource.CLOSED) {
        console.log('connection is closed')
      } else {
        console.log('Error occured', event)
      }
      // close方法用于关闭连接
      source.close()
    })
    source.addEventListener(
      'customEvent',
      function (e) {
        console.log(e.lastEventId)
        console.log(e.data)
      },
      false,
    )
  } else {
    console.log('浏览器不支持SSE')
  }
}
</script>

<style scope>
/* 总体布局的样式部分 */
#layout-container {
  height: 100%;
}
#layout-container .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color 0.3s;
}

#layout-container .trigger:hover {
  color: #1890ff;
}

#layout-container .logo {
  height: 32px;
  background: rgba(255, 255, 255, 0.3);
  margin: 16px;
  text-align: center;
  color: white;
  font-weight: bold;
  line-height: 32px;
}

.site-layout .site-layout-background {
  background: #fff;
}
/* 与AI交互的界面部分样式 */
#footer-container div {
  height: 100%;
}
#footer-container textarea {
  font-size: 25px;
  padding-bottom: 100px;
  margin: 5px;
}

#chat-msgs-container {
  height: 100%;
  padding: 20px;
  position: relative;
  display: flex;
  flex-direction: column;
}
.self-msg-container {
  text-align: right;
  padding: 0px 20px;
}
.self-msg {
  background-color: #edf3fe;
  border-radius: 20px;
  padding: 15px;
  display: inline-block;
  margin-top: 20px;
  margin-left: 50px;
  text-align: left;
  line-height: 1.2;
}
.ai-msg-container think {
  display: block;
  margin-bottom: 10px;
}
.ai-msg-container {
  line-height: 1.5;
  text-align: left;
  margin-right: 50px;
  font-size: 25px;
  height: 100%;
  overflow-y: auto;
}
.currentUser {
  position: fixed;
  right: 10px;
}
.history {
  color: #fff;
  margin: 20px;
}
.history a:link,
.history :active,
.history :visited {
  color: #fff;
}
</style>
